import axios from 'axios'
import { message } from '@/components/message/message'
import { AxiosResponse } from 'axios'
import { AxiosError } from 'axios'
import { InternalAxiosRequestConfig } from 'axios'
export const baseURL = '/c12100/axios/'

const axiosInstance = axios.create({
    //自动加在url前面
    baseURL: baseURL,
    //超时时间 ms
    timeout: 5000,
    headers: {
        //myheader_xxx: "123", //
        post: {},
        get: {}
    },
    //跨域凭证，
    withCredentials: true, //如果这里为false，那么服务端设置了[htto-only]set-cookie 这里就不会自动带上
    withXSRFToken: false
})

//响应和请求 拦截器配置
axiosInstance.interceptors.request.use(
    (config: InternalAxiosRequestConfig) => {
        return config
    },
    (error: AxiosError) => {
        return Promise.reject(error)
    }
)

// 后置拦截器（获取到响应时的拦截）
axiosInstance.interceptors.response.use(
    (response: AxiosResponse) => {
        return response
    },
    (error: AxiosError) => {
        if (error.response && error.response.data) {
            const code = error.response.status
            const msg = error.response.data['title']
            message.error(`[${code}]${msg}`)
        }
        return Promise.reject(error)
    }
)

export default axiosInstance
